/**
 * 
 */
package com.ai.dmc.index.service.indicatorstore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ai.dmc.index.base.impl.base.BaseServiceImpl;
import com.ai.dmc.index.base.sequence.SequenceGenerator;
import com.ai.dmc.index.common.data.PubConstant;
import com.ai.dmc.index.common.exception.BusinessException;
import com.ai.dmc.index.intf.service.indicatorstore.IIndicatorStoreService;
import com.ai.dmc.utils.json.JsonUtil;
import com.ai.dmc.utils.string.StringUtil;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;

/**
 * Title： 指标超市展示层service 
 * Description： 指标超市展示层service 
 * Copyright：Copyright (c)2009
 * Company：北京亚信智慧数据科技有限公司
 * @author lg, 2016年1月6日
 * @version 1.0
 */
public class IndicatorStoreServiceImpl extends BaseServiceImpl implements IIndicatorStoreService {

    // 定义对应Mapper文件的命名空间
    private static final String NAMESPACE = "IIndicatorStoreDao.";
    
    public static Logger log = LoggerFactory.getServiceLog(IndicatorStoreServiceImpl.class);

    private SequenceGenerator sequenceGenerator;

    public void setSequenceGenerator(SequenceGenerator sequenceGenerator) {
        this.sequenceGenerator = sequenceGenerator;
    }

//    private IPrivilegeService privilege;
//    
//    public void setPrivilege(IPrivilegeService privilege){
//        this.privilege = privilege;
//    }
    
    @Override
    public void selectIndicatorFolderInfo(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        // FOLDER_INFO
//        List<String> folderList = null;
//        try {
//            folderList = privilege.getFolder(inputObject);
//        } catch (Exception e) {
//            throw new BusinessException(e.getMessage());
//        }
        List<Map<String, String>> idxFolderInfo = this.getBaseDao().queryForList(
                NAMESPACE + "selectIndicatorFolderInfo", inputObject.getParams());
        //过滤用户目录权限
//        if(null != folderList){
//            String id = null;
//            for(int i=0;i<idxFolderInfo.size();i++){
//                id = idxFolderInfo.get(i).get("id");
//                if(!folderList.contains(id)){
//                   idxFolderInfo.remove(i);
//                   i--;
//                }
//            }
//        }
        // USER_FOLDER
        List<Map<String, String>> idxUserFolder = this.getBaseDao().queryForList(
                NAMESPACE + "selectIndicatorUserFolder", inputObject.getParams());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("FOLDER_INFO", null == idxFolderInfo ? "" : JsonUtil.Object2Json(idxFolderInfo));
        resultMap.put("USER_FOLDER", null == idxUserFolder ? "" : JsonUtil.Object2Json(idxUserFolder));
        outputObject.setObject(JsonUtil.Object2Json(resultMap));
    }

    @Override
    public void selectCommonDimInfo(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        // 查询维度配置信息
        List<Map<String, String>> idxDimCfgInfoList = selectDimCfgInfo(inputObject.getParams());
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        // 查询维度的详细信息
        for (Map<String, String> idxDimCfgInfo : idxDimCfgInfoList) {
            // 是否读度维度表
            if ((PubConstant.IS_READ_TABLE_FLAG).equals(idxDimCfgInfo.get("tableFlag"))) {
                // 维度表名
                String dimTableName = idxDimCfgInfo.get("dimTableName");
                // 维度编码
                String dimTableColumnCode = idxDimCfgInfo.get("dimTableColumnCode");
                // 维度名称
                String dimTableColumnName = idxDimCfgInfo.get("dimTableColumnName");
                if (null != dimTableName && null != dimTableColumnCode && null != dimTableColumnName
                        && !("").equals(dimTableName) && !("").equals(dimTableColumnCode)
                        && !("").equals(dimTableColumnName)) {
                    String querySql = "select " + dimTableColumnCode + " as \"id\"," + dimTableColumnName 
                            + " as \"name\" from " + dimTableName;
                    Map<String, String> paraMap = new HashMap<String, String>();
                    paraMap.put("querySql", querySql);
                    // 查询详细信息
                    List<Map<String, String>> dimInfoList = this.getBaseDao().queryForList(
                            NAMESPACE + "selectDimInfoList", paraMap);
                    Map<String, Object> resultMap = new HashMap<String, Object>();
                    resultMap.putAll(idxDimCfgInfo);
                    resultMap.put("dimInfoList", dimInfoList);
                    resultList.add(resultMap);
                }
            } else {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.putAll(idxDimCfgInfo);
                resultList.add(resultMap);
            }

        }
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("FOLDER_INFO", resultList);
        outputObject.setObject(resultMap);
    }

    @Override
    public void selectIndicatorsInfo(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        //查询维度配置信息,根据维度配置信息过滤查询指标ID集合
        Map<String, Object> idxDimCfgInfoMap = makeSelectIdxParmList(inputObject.getParams());
//        List<Map<String, Object>> idxIdInfoList = this.getBaseDao().queryForListByObjectMap(
//                NAMESPACE + "selectIdxIdInfoList", idxDimCfgInfoMap);
//        StringBuffer idxIdInfoSbf = new StringBuffer();
//        for (Map<String, Object> idxIdInfo : idxIdInfoList) {
//            if (null != idxIdInfoSbf && idxIdInfoSbf.length() > 0) {
//                idxIdInfoSbf.append(" or ");
//            }
//            idxIdInfoSbf.append("( info.idx_id = ");
//            idxIdInfoSbf.append(idxIdInfo.get("idxId"));
//            idxIdInfoSbf.append(" and info.version_code = ");
//            idxIdInfoSbf.append(idxIdInfo.get("versionCode"));
//            idxIdInfoSbf.append(" )");
//        }
        String paraName = inputObject.getParams().get("paraName");
        Map<String,Object> parmMap = new HashMap<String,Object>();
        parmMap.putAll(inputObject.getParams());
        parmMap.putAll(idxDimCfgInfoMap);
        //parmMap.put("idxIdInfo", (null != idxIdInfoList && idxIdInfoList.size() > 0) ? idxIdInfoSbf.toString() : "");
        parmMap.put("paraName", (StringUtil.isNotEmpty(paraName)) ? paraName : "");
        int totalRecord = 0;
        List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
        //if (null != idxIdInfoSbf && idxIdInfoSbf.length() > 0) {
            totalRecord = this.getBaseDao().getTotalCountByObjectMap(NAMESPACE + "selectIndicatorsInfoTotalCount", parmMap);
            List<Map<String, String>> indicatorsInfoList = this.getBaseDao().queryForPageListByObjectMap2(
                    NAMESPACE + "selectIndicatorsInfo", parmMap);
            // 结果集里面加入是否组装，是否关注
            for (Map<String, String> indicatorsInfo : indicatorsInfoList) {
                inputObject.getParams().put("indicatorId", indicatorsInfo.get("idxId"));
                // 查询指标是否关注
                String isFollow = isFollowOrAssemble(inputObject.getParams(), "selectIsFollow");
                // 查询指标是否组装
                String isAssemble = isFollowOrAssemble(inputObject.getParams(), "selectIsAssemble");
                indicatorsInfo.put("isFollow", isFollow);
                indicatorsInfo.put("isAssemble", isAssemble);
                indicatorsInfo.put("idxFolderPath", getIdxFolderPath(String.valueOf(indicatorsInfo.get("folderId"))));
                resultList.add(indicatorsInfo);
            }
        //}
        Map<String, String> totalMap = new HashMap<String, String>();
        totalMap.put("dataTotal", String.valueOf(totalRecord));
        outputObject.setBean(totalMap);
        outputObject.setBeans(resultList);
    }
    
    /*
     * 指标分类路径(获取当前分类级别，查询父节点名称)
     */
    private String getIdxFolderPath(String folderId){
        String result = "";
        String folderNameOne = "";
        String folderNameTwo = "";
        String folderNameThree = "";
        if (null != folderId && !("").equals(folderId)) {
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("folderId", folderId);
            // 获取当前分类级别
            String levelCode = (String) this.getBaseDao().queryForObject(NAMESPACE + "selectIndexFolderLevelCode",
                    paraMap);
            if (PubConstant.FOLDER_LEVEL_CODE_ONE.equals(levelCode)) {
                // 通过Code查询分类名称
                Map<String, String> mapOne = selectFolderInfo(folderId);
                if (null != mapOne.get("folderName")) {
                    folderNameOne = mapOne.get("folderName");
                }
                result = folderNameOne;
            } else if (PubConstant.FOLDER_LEVEL_CODE_TWO.equals(levelCode)) {
                Map<String, String> mapTwo = selectFolderInfo(folderId);
                if (null != mapTwo.get("parentFolderId")) {
                    Map<String, String> mapOne = selectFolderInfo(String.valueOf(mapTwo.get("parentFolderId")));
                    if (null != mapOne.get("folderName")) {
                        folderNameOne = mapOne.get("folderName");
                    }
                }
                folderNameTwo = mapTwo.get("folderName") == null ? folderNameTwo : mapTwo.get("folderName");
                if(null != folderNameOne && folderNameOne.length() >0){
                    result = folderNameOne + "->";
                }
                if(null != folderNameTwo && folderNameTwo.length() >0){
                    result = result + folderNameTwo;
                }
            } else {
                Map<String, String> mapThree = selectFolderInfo(folderId);
                if (null != mapThree.get("parentFolderId")) {
                    Map<String, String> mapTwo = selectFolderInfo(String.valueOf(mapThree.get("parentFolderId")));
                    if (null != mapTwo && null != mapTwo.get("parentFolderId")) {
                        Map<String, String> mapOne = selectFolderInfo(String.valueOf(mapTwo.get("parentFolderId")));
                        if (null != mapOne.get("folderName")) {
                            folderNameOne = mapOne.get("folderName");
                        }
                    }
                    folderNameTwo = mapTwo.get("folderName") == null ? folderNameTwo : mapTwo.get("folderName");
                }
                folderNameThree = mapThree.get("folderName") == null ? folderNameThree : mapThree.get("folderName");
                if(null != folderNameOne && folderNameOne.length() >0){
                    result = folderNameOne + "->";
                }
                if(null != folderNameTwo && folderNameTwo.length() >0){
                    result = result + folderNameTwo+"->";
                }
                if(null != folderNameThree && folderNameThree.length() >0){
                    result = result + folderNameThree;
                }
            }
        }
        return result;
    }
    /*
     *通过Code查询分类名称
     */
    @SuppressWarnings("unchecked")
    private Map<String,String> selectFolderInfo(String folderId) {
        Map<String,String> paraMap = new HashMap<String,String>();
        paraMap.put("folderId", folderId);
        Map<String,String> resultMap = null;
        resultMap = (Map<String,String>) this.getBaseDao().queryForObject(NAMESPACE + "selectFolderInfoByCode"
                , paraMap);
        if(null == resultMap){
            resultMap = new HashMap<String,String>();
        }
        return resultMap;
    }
    /*
     * 解析查询参数  JSONArray字符串
     */
    private List<String> analyJSONArrayParm(String jsonArrayStr) {
        List<String> whereList = new ArrayList<String>();
        if (null != jsonArrayStr && !("").equals(jsonArrayStr)) {
            List<Map<String, String>> jsonArrayList = JsonUtil.jsonArrayToListMap(JsonUtil
                    .Object2JsonArray(jsonArrayStr));
            for (Map<String, String> jsonArrayMap : jsonArrayList) {
                //key--value--partFlag
                String key = jsonArrayMap.get("key");
                String value = jsonArrayMap.get("value");
                String partFlag = jsonArrayMap.get("partFlag");
                if(null!=value&&!("").equals(value)){
                    if (PubConstant.IS_PART_FLAG.equals(partFlag)) {
                        String[] valueArray = value.split(PubConstant.PART_FLAG);
                        if (null != valueArray && valueArray.length == 2) {
                            key = key.replace("{parm1}", valueArray[0]).replace("{parm2}", valueArray[1]);
                        }
                    } else {
                        if (value.indexOf(",") > -1 && key.indexOf("find_in_set('{parm}'") > -1
                                && (key.indexOf("like {parm}") < 0 && key.indexOf("{parm} like") < 0)) {
                            String[] valueArray = value.split(",");
                            for (String strVal : valueArray) {
                                key = jsonArrayMap.get("key");
                                key = key.replace("{parm}", strVal);
                                whereList.add(key);
                            }
                        } else if (value.indexOf(",") > -1 && key.indexOf("find_in_set('{parm}'") < 0
                                && key.indexOf("find_in_set") > -1
                                && (key.indexOf("like {parm}") < 0 && key.indexOf("{parm} like") < 0)) {
                            key = key.replace("{parm}", value);
                            whereList.add(key);
                        } else if (key.indexOf("like {parm}") > -1) {
                            key = key.replace("{parm}", "concat('%',concat('" + value + "','%'))");
                            whereList.add(key);
                        } else if (key.indexOf("{parm} like") > -1) {
                            String[] keyArray = key.split("like");
                            if (null != keyArray && keyArray.length == 2) {
                                key = "'" + value + "' " + "like concat('%',concat('" + keyArray[1].trim() + "','%'))";
                            }
                            whereList.add(key);
                        } else {
                            key = key.replace("{parm}", value);
                            whereList.add(key);
                        }
                    }

                }

            }
        }
        return whereList;
    }
    @Override
    public void doIndicatorAttenOrCancel(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        // 关注类型:1:关注，2：取消关注
        String type = inputObject.getParams().get("type");
        if (PubConstant.INDEX_ATTEN_TYPE.equals(type)) {
            // 关注
            this.getBaseDao().insert(NAMESPACE + "insertIndictorAttenStatus", inputObject.getParams());
        } else {
            // 取消关注
            this.getBaseDao().delete(NAMESPACE + "deleteIndictorAttenStatus", inputObject.getParams());
        }

    }

    @Override
    public void selectIndicatorAttenFolder(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        List<Map<String, String>> idxAttenFolder = this.getBaseDao().queryForList(
                NAMESPACE + "selectIndicatorAttenFolder", inputObject.getParams());
        outputObject.setObject(null == idxAttenFolder ? "" : idxAttenFolder);
    }

    @Override
    public void createIndicatorAttenFolder(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        // 创建目录时校验名称唯一性
        List<Map<String, String>> attenFolderNameList = this.getBaseDao().queryForList(NAMESPACE + "queryAttenFolderNameList", inputObject.getParams());
        if(null!=attenFolderNameList&&attenFolderNameList.size()>0){
            Map<String,String> resultMap = new HashMap<String,String>();
            resultMap.put("resultCode", PubConstant.ATTEN_FOLDER_NAME_REPEAT);
            outputObject.setBean(resultMap);
        }else{
            // 调用公共方法生成目录ID attenFolderID
            String attenFolderId = sequenceGenerator.getNextValue(PubConstant.INDEX_ATTEN_FOLDER_ID_KEY);
            inputObject.getParams().put("attenFolderId", attenFolderId);
            this.getBaseDao().insert(NAMESPACE + "createIndicatorAttenFolder", inputObject.getParams());
            Map<String,String> resultMap = new HashMap<String,String>();
            resultMap.put("resultCode", PubConstant.ATTEN_FOLDER_NAME_SUCCESS);
            outputObject.setBean(resultMap);
        }
    }

    @Override
    public void deleteIndicatorAttenFolder(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        this.getBaseDao().delete(NAMESPACE + "deleteIndicatorAttenFolder", inputObject.getParams());
    }

    @Override
    public void updateUserIndicatorFolder(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        // 先删除此用户所有的一级指标分类再进行插入
        this.getBaseDao().delete(NAMESPACE + "deleteUserIndicatorFolder", inputObject.getParams());
        //循环list
        String  jsonArray = inputObject.getParams().get("userFolderArray");
        List<Map<String,String>> userFolderList = JsonUtil.jsonArrayToListMap(JsonUtil.Object2JsonArray(jsonArray));
        List<Map<String,String>> paraList = new ArrayList<Map<String,String>>();
        if(null!=userFolderList&&userFolderList.size()>0){
            for(Map<String,String> userFolderMap:userFolderList){
                userFolderMap.put("userId", inputObject.getParams().get("userId"));
                paraList.add(userFolderMap);
            }
            this.getBaseDao().insert(NAMESPACE + "addUserIndicatorFolder", paraList);
        }
    }

    @Override
    public void addIndicatorAssembleCount(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        this.getBaseDao().insert(NAMESPACE + "addIndicatorAssembleCount", inputObject.getParams());
    }

    @Override
    public void selectIndicatorAssembleCount(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        int idxAssembleCount = this.getBaseDao().getTotalCount(NAMESPACE + "selectIndicatorAssembleCount",
                inputObject.getParams());
        Map<String,String> countMap = new HashMap<String,String>();
        countMap.put("countNum", String.valueOf(idxAssembleCount));
        outputObject.setObject(countMap);
    }

    @Override
    public void selectIndicatorBaseInfoByVersion(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        Map<String, String> idxDetailInfoMap = selectIdxDetailInfo(inputObject.getParams());
        outputObject.setObject(idxDetailInfoMap);
    }

    @Override
    public void selectIndicatorBaseInfo(InputObject inputObject, OutputObject outputObject) throws BusinessException {
        // 根据指标ID进行查询所有版本号按降序排序，最新的版本号排在第一个 VERSION_INFO
        List<Map<String, String>> idxVersionCodeList = this.getBaseDao().queryForList(
                NAMESPACE + "selectIdxVersionCodeListInfo", inputObject.getParams());
        // 根据指标ID、最新的版本号 查询指标详细信息 NEW_VERSION_DETAILINFO
        Map<String, String> idxDetailInfoMap = null;
        if (null != idxVersionCodeList && idxVersionCodeList.size() > 0) {
            String newVersionCode = idxVersionCodeList.get(0).get("versionCode");
            if (null != inputObject.getParams().get("versionCode")
                    && !("").equals(inputObject.getParams().get("versionCode"))) {
                idxDetailInfoMap = selectIdxDetailInfo(inputObject.getParams());
            }else{
                inputObject.getParams().put("versionCode", newVersionCode);
                idxDetailInfoMap = selectIdxDetailInfo(inputObject.getParams());
            }
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("VERSION_INFO", idxVersionCodeList);
        resultMap.put("NEW_VERSION_DETAILINFO", idxDetailInfoMap);
        outputObject.setObject(resultMap);
    }

    /**
     * 查询指标版本的详细信息(指标ID，指标版本号)
     */

    private Map<String, String> selectIdxDetailInfo(Map<String, String> paraMap) {
        @SuppressWarnings("unchecked")
        Map<String, String> idxDetailInfoMap = (Map<String, String>) this.getBaseDao().queryForObject(
                NAMESPACE + "selectIndicatorDetailInfo", paraMap);
        idxDetailInfoMap.put("idxFolderPath", getIdxFolderPath(String.valueOf(idxDetailInfoMap.get("folderId"))));
        return idxDetailInfoMap;
    }

    /*
     * 查询维度配置信息 (td_idx_qury_dimtabs_cfg)
     */
    private List<Map<String, String>> selectDimCfgInfo(Map<String, String> paraMap) {
        List<Map<String, String>> idxDimCfgInfo = this.getBaseDao().queryForList(
                NAMESPACE + "selectDimCfgInfo",paraMap);
        return idxDimCfgInfo;
    }
    
    /*
     * 判断指标（关注，组装）是否存在(1：存在，2：不存在)
     */
    private String isFollowOrAssemble(Map<String,String> paraMap,String sqlId){
        String idxId = (String) this.getBaseDao().queryForObject(NAMESPACE + sqlId, paraMap);
        if(null!=idxId && !("").equals(idxId)){
            return PubConstant.EXIST_FLAG;
        }else{
            return PubConstant.EXIST_NOT_FLAG;
        }
    }
    /*
     * 
     */
    private Map<String,Object>  makeSelectIdxParmList(Map<String, String> paraMap){
        Map<String,Object> resultList = new HashMap<String,Object>();
        //left-join集合
        List<String> leftJoinList = new ArrayList<String>();
        //where条件集合
        List<String> whereList = new ArrayList<String>();
        List<Map<String, String>> idxDimCfgInfoList = selectDimCfgInfo(paraMap);
        for(Map<String, String> idxDimCfgInfo:idxDimCfgInfoList){
            //主表名称
           String masterTableName =  idxDimCfgInfo.get("masterTableName");
           //关联字段
           String joinColumn = idxDimCfgInfo.get("joinColumn");
           //主表关联字段
           //String masterTableColumn = idxDimCfgInfo.get("masterTableColumn");
           if(!(PubConstant.IDX_MASTER_TABLE_NAME).equals(masterTableName)){
               StringBuffer sbf = new StringBuffer();
               sbf.append("left join");
               sbf.append("(");
               sbf.append(masterTableName);
               sbf.append(")");
               sbf.append(" "+idxDimCfgInfo.get("tableOtherName"));
               sbf.append(" on ");
               if(joinColumn.indexOf(",")>-1){
                   String[] joinColumnArr = joinColumn.split(",");
                   for(int i = 0;i<joinColumnArr.length;i++){
                       if(i!=0){
                           sbf.append(" and "); 
                       }
                       sbf.append(idxDimCfgInfo.get("tableOtherName") + "." + joinColumnArr[i] + " = ");
                       sbf.append( PubConstant.IDX_TABLE_OTHER_NAME+"." + joinColumnArr[i]);
                   }
               }else{
                   sbf.append(idxDimCfgInfo.get("tableOtherName") + "." + joinColumn + " = ");
                   sbf.append( PubConstant.IDX_TABLE_OTHER_NAME+"." + joinColumn);
               }
               leftJoinList.add(sbf.toString());
           }
        }
        //解析查询参数 whereInfo key--value--partFlag
        String whereInfo = paraMap.get("indexSelectArray");
        whereList = analyJSONArrayParm(whereInfo);
        resultList.put("leftJoinList", leftJoinList);
        resultList.put("whereList", whereList);
        return resultList;
    }
}
